package org.example.manage;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.example.model.MilkTea;
import org.example.model.Order;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public abstract class ObjectManage<T> {
    private String fileName = null;
    public List<T> objectList = new ArrayList<>();
    public int type;
    public List<T> read() {
        File file = new File(fileName);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = "";
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileReader reader = new FileReader(file.getAbsoluteFile());
            BufferedReader bufferedReader = new BufferedReader(reader);
            while(true){
                int n = bufferedReader.read();
                if(n!=-1){
                    json = String.format("%s%c", json,(char)n);
                }
                else break;
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (type == 1) {
            objectList = gson.fromJson(json, new TypeToken<List<MilkTea>>() {}.getType());
        }
        if (type == 2) {
            objectList = gson.fromJson(json, new TypeToken<List<Order>>() {}.getType());

        }
        return objectList;
    }
    public void save(T item) {
        if (item !=null) {
            if (read() == null) {
                objectList = new ArrayList<>();
            }
        }
        if (item != null) {
            objectList.add(item);
        }
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(objectList);
        File file = new File(fileName);
        try {
            FileWriter writer = new FileWriter(file.getAbsoluteFile(),false);
            BufferedWriter bufferedWriter = new BufferedWriter(writer);
            bufferedWriter.write(json);
            bufferedWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public void update(T item, T uItem) {
        if (objectList.isEmpty()) {
            objectList = read();
        }
        int n = getAt(item);
        objectList.set(n, uItem);
        save(null);
    }
    public void move(T item) {
        if (objectList.isEmpty()) {
            objectList = read();
        }
        objectList.remove(getAt(item));
        save(null);
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public int getAt(T item) {
        for (int i = 0; i < objectList.size(); i++) {
            if (compare(objectList.get(i), item)) {
                return i;
            }
        }
        return -1;
    }
    public abstract boolean compare(T item, T uItem);
}
